package com.example.monitorsms;

import android.annotation.SuppressLint;
import android.app.Application;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.os.Vibrator;

import com.example.monitorsms.http.CommonHttpUtil;
import com.example.monitorsms.http.HttpClient;
import com.example.monitorsms.utils.LogUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.SPCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

public class MyApp extends Application {
    private static Application mContext;
    public static Vibrator vibrator;
    public static MediaPlayer mMediaPlayer;
    public static AudioManager mAudioManager;
    public static int soundCount;//播放循环次数
    public static int audioOk = 5;
    public static String tipsOk = "交警";
    public static String PushOk = "交管";

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        LogUtils.setIsDebug(true);
        CommonHttpUtil.init();
        //---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//
        HttpHeaders headers = new HttpHeaders();
        headers.put("Content-Type", "application/json");//header不支持中文，不允许有特殊字符
        headers.put("dateType", "json");
        headers.put("charset", "UTF-8");
        //-----------------------------------------------------------------------------------//

        //构建OkHttpClient.Builder
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        //配置log打印级别
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        //loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.NONE);
        //log颜色级别，决定了log在控制台显示的颜色
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addInterceptor(loggingInterceptor);

        //全局的读取超时时间
        builder.readTimeout(HttpClient.TIMEOUT, TimeUnit.MILLISECONDS);
        //全局的写入超时时间
        builder.writeTimeout(HttpClient.TIMEOUT, TimeUnit.MILLISECONDS);
        //链接超时时间
        builder.connectTimeout(HttpClient.TIMEOUT, TimeUnit.MILLISECONDS);

        //使用sp保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));

        //以下设置的所有参数是全局参数,同样的参数可以在请求的时候再设置一遍,那么对于该请求来讲,请求中的参数会覆盖全局参数
        //好处是全局参数统一,特定请求可以特别定制参数
        try {
            OkGo.getInstance().init(this)//必须调用初始化
                    //以下都不是必须的，根据需要自行选择
                    .setOkHttpClient(builder.build())
                    //可以全局统一设置缓存模式,默认是不使用缓存,可以不传,具体其他模式看 github 介绍 https://github.com/jeasonlzy/
                    // .setCacheMode(CacheMode.NO_CACHE)
                    //可以全局统一设置缓存时间,默认永不过期,具体使用方法看 github 介绍
                    // .setCacheTime(7)
                    //可以全局统一设置超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0
                    .setRetryCount(0)
                    //这两行同上，不需要就不要加入
                    .addCommonHeaders(headers);//设置全局公共头
            //.addCommonParams(params);//设置全局公共参数
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Application getContext() {
        return mContext;
    }

    public static void setRouse() {
        //屏幕唤醒
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        @SuppressLint("InvalidWakeLockTag")
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.SCREEN_DIM_WAKE_LOCK, "BootBroadcastReceiver");
        wl.acquire();
        //屏幕解锁
        KeyguardManager km = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock kl = km.newKeyguardLock("BootBroadcastReceiver");
        kl.disableKeyguard();
//        Intent intent = new Intent();
//        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
//            Intent newIntent = new Intent(mContext, MainActivity.class);
//            newIntent.setAction("android.intent.action.MAIN");
//            newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            mContext.startActivity(newIntent);
//        }
    }

    public static void setVibrate() {
        vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
        long[] patern = {0, 1000, 1000};
        AudioAttributes audioAttributes = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .build();
            vibrator.vibrate(patern, 1, audioAttributes);
        } else {
            vibrator.vibrate(patern, 1);
        }
    }

    public static void setPlayer1() {
        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        //获取媒体音量最大值
        int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        LogUtils.e("TAG", "max:" + max);
        //获取系统当前媒体音量
        int volume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        LogUtils.e("TAG", "volume:" + volume);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioOk, 0);
        mMediaPlayer = MediaPlayer.create(mContext, R.raw.text2audio);
        mMediaPlayer.start();
    }

    public static void setPlayer() {
        soundCount = 0;
        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        //获取媒体音量最大值
        int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        LogUtils.e("TAG", "max:" + max);
        //获取系统当前媒体音量
        int volume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        LogUtils.e("TAG", "volume:" + volume);
        //设置音量最大值的一半
        // mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, (int) (max / 2), 0);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioOk, 0);
        mMediaPlayer = MediaPlayer.create(mContext, R.raw.text2audio);
        mMediaPlayer.start();

        mMediaPlayer.setOnCompletionListener(mp -> {
            if (soundCount <= 2) {
                new Handler().postDelayed(() -> {
                    mMediaPlayer.start();
                    soundCount++;
                }, 2000);
            }
        });
    }
}
